import { nextTick } from "vue";
import router from "./router";
import nProgress from "nprogress";
import { useUserStore } from "@/store/modules/user";
import { useGlobalStore } from "@/store/modules/global";
import { generateRouter } from "./router";

// 白名单，里面是路由对象的name
const WhiteList = ["login", "dashboard"];
// 设置页面标题
const getPageTitle = (title) => {
  const { currentTitle } = useGlobalStore();
  if (title) {
    return `${title} - ${currentTitle.value}`;
  }
  return currentTitle.value;
};

// ----------------------- 路由加载前 -----------------------

router.beforeEach(async (to, from) => {
  nProgress.start();
  const useUser = useUserStore();
  await generateRouter();
  const token = useUser.currentUserInfo.token;
  if (!token && !WhiteList.includes(to.name)) {
    return {
      name: "login",
      query: {
        redirect: to.fullPath,
      },
      replace: true,
    };
  }
  if (token && WhiteList.includes(to.name)) {
    return from.path ? from.path : "/";
  }
});
// ----------------------- 路由加载后 -----------------------
router.afterEach((to) => {
  nProgress.done();
  nextTick(() => {
    document.title = getPageTitle(to.meta.title ? to.meta.title : "");
  });
});
